<?php

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------
namespace Home\Controller;
use Think\Controller;
use Home\Controller\BaseController;

class PayController extends BaseController {

    //根据用户的SESSION判断数据库里是否有此用户
    public function _initialize() {
        parent::_initialize();
        $userID = session('user_id');
        $forward = I('forwards');
        $loginUrl = HOME_URL . '/Login/index?forward=' . $forward;
        if (!empty($userID)) {
            $re = M('Users')->where('user_id=%d', $userID)->find();
            if (!$re) {
                $this->error('您的账户存在异常不能进行此操作！');
            }
        } else {
            redirect($loginUrl);
        }
    }

    public function index() {
        //页面上通过表单选择在线支付类型，支付宝为alipay 财付通为tenpay
        $paytype = I('get.paytype');
        $order_no = I('id');

        //在此之前goods1的业务订单已经生成，状态为等待支付
        $map['pay_sn'] = $order_no;
        $order = M('order')->where($map)->count();
        //单个支付和合并支付
        if ($order == 1) {
            //循环获取订单的总价格和商品
            $orders = M('order')->where('pay_sn=%s', array($order_no))->find();
            //获取订单下的商品
            $orderGoods = M('order_goods')->where('order_id=%s', array($orders['order_id']))->select();
            foreach ($orderGoods as $key => $value) {
                $title .= $value['goods_title'] . '；';
            }
            $title = "共" . count($orderGoods) . "件商品：" . sub_str($title, 0, 22);
            $payPrice = $orders['goods_amount'];
        } else {
            $orders = M('order')->where('pay_sn=%s', array($order_no))->select();
            foreach ($orders as $key => $value) {
                $payPrice += $value['goods_amount'];
            }
            $title = "合并支付丨" . $order . "笔订单";
        }
        
        //获取平台的优惠券的信息
        $map['pay_sn'] = $order_no;
        $map['voucher_store'] = 0;
        $tddList = M('order_voucher')->where($map)->select();
        if(!empty($tddList)){
            foreach ($tddList as $key => $value) {
                $totalTdd += $value['voucher_price'];
            }
            $payPrice = $payPrice-$totalTdd;
        }
        
        if (empty($orders)) {
            $this->error('此订单不存在请确认是否有此订单！', WEIXIN_URL . U('/Order/index'));
        }
        if ($orders['order_state'] == 20) {
            $this->error('此订单已经支付成功，不需要在次支付！', WEIXIN_URL . U('/Order/index'));
        } else {
            $pay = new \Libs\Pay($paytype, C('PAY_' . $paytype));
            $vo = new \Libs\Pay\PayVo();
            $vo->setBody($title)
                    ->setFee($payPrice) //支付金额
                    ->setOrderNo($order_no)
                    ->setTitle($title)
                    ->setCallback("Home/Pay/tradePay")
                    ->setUrl(U("/Pay/result"))
                    ->setParam(array('order_id' => "淘嘟嘟商城业务订单", 'paytype' => $paytype));
            echo $pay->buildRequestForm($vo);
        }
    }

    /**
     * 订单支付成功
     * @param type $money
     * @param type $param  trade_id
     */
    public function tradePay($money, $param) {
        if (session("pay_verify") == true) {
            session("pay_verify", null);
            //M("order")->where(array('pay_sn' => $param))->save(array('order_state' => 20, 'order_amount' => $money, 'payment_time' => time()));
            //计算出多订单的相关支付的价格（除去优惠券实际支付的价格）
            $map['pay_sn'] = $param;
            $oModel = D('Order');
            $oList = $oModel->relation('OrderGoods')->where($map)->select();
            //获取平台的优惠券的信息
            $maps['pay_sn'] = $param;
            $maps['voucher_store'] = 0;
            $tddList = M('order_voucher')->where($maps)->select();
            if (!empty($tddList)) {
                foreach ($tddList as $key => $value) {
                    $totalTdd += $value['voucher_price'];
                }
            }
            $bili = (1 - $totalTdd/($money+$totalTdd)); //平台优惠比例
            foreach ($oList as $key => $value) {
                if ($value['discount_fee'] > 0) {
                    foreach ($value['OrderGoods'] as $k => $v) {
                        $pay_price[$k] = $bili * $v['goods_price'] * $v['goods_num'];
                        $trader_price += $bili * $v['goods_price'] * $v['goods_num'];
                    }
                    $bili2 = (1 - ($value['discount_fee']/$trader_price));
                    //根据占比更新单个商品时间支付的价格
                    foreach ($value['OrderGoods'] as $k => $v) {
                        //更新实际支付的价格
                        $pay[$k] = $bili2 * $pay_price[$k];
                        //在根据店铺的优惠比例继续计算实际支付的价格
                        M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay[$k]));
                        $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                    }
                    //更新订单的价格及状态
                    M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                } else {
                    //根据占比更新单个商品时间支付的价格
                    foreach ($value['OrderGoods'] as $k => $v) {
                        //更新实际支付的价格
                        $pay_price[$k] = $bili * $v['goods_price']*$v['goods_num'];
                        M('OrderGoods')->where(array('order_id' => $v['order_id'], 'goods_id' => $v['goods_id']))->save(array('goods_pay_price' => $pay_price[$k]));
                        $total_price[$key] += $pay_price[$k];  //计算出订单的总价格
                    }
                    //更新订单的价格及状态
                    M("order")->where(array('order_id' => $value['order_id']))->save(array('order_state' => 20, 'order_amount' => $total_price[$key], 'payment_time' => time()));
                }
            }

        } else {
            E("Access Denied");
        }
    }

//    public function payCheck() {
//        //$param = I('trade_id');
//        //处理goods1业务订单、改名good1业务订单状态
//        ///M("Order")->where(array('pay_sn' => $param))->save(array('status' => $status, 'payment' => $money, 'pay_time' => time()));
//    }

    //
    public function result() {
        $out_trade_no = I('out_trade_no');
        $trade_id = auth_decode($out_trade_no);
        $map['pay_sn'] = $trade_id ;
        $pay = M('orderPay')->where($map)->find();
        $this->assign('pay', $pay);
        $this->display();
    }
    
}
